package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosRelationDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosUserDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.CommonUtil;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.IKitePosSceneHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.KitePosHandlerContext;
import com.iwhalecloud.bss.kite.cucc.service.util.ChangeTypeUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class KitePosMemRelationHandler extends KitePosBaseRelationHandler implements IKitePosSceneHandler {
    @Override
    public void handle(KitePosHandlerContext context) {
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());
        if (!KiteStringUtils
            .equalsAny(kiteSceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_JOIN,
                LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_QUIT)) {
            return;
        }

        List<KitePosUserDTO> mainUsers = (List<KitePosUserDTO>) querySceneInstService.getExtParameterValue(context.getSceneInstId(), "serialNumber");
        List<KitePosRelationDTO> relations = Lists.newArrayList();
        List<Map<String, Object>> relationRoleList = queryRelation(context.getSceneInstId(), "2");

        List<KiteInst> memOfferInsts = querySceneInstService
            .listInsts(context.getSceneInstId(), Lists.newArrayList(InstType.MEM_OFFER_INST)).stream().filter(
                offerInst -> KiteStringUtils
                    .equalsAny(offerInst.getActionType().name(), ActionType.K.name(), ActionType.A.name(),
                        ActionType.M.name(), ActionType.D.name())).collect(Collectors.toList());

        int index = 1;
        for (KiteInst memOfferInst : memOfferInsts) {
            String userInfoJson = memOfferInst.getAttrValue("userInfo");
            if (KiteStringUtils.isEmpty(userInfoJson)) {
                continue;
            }
            List<KitePosUserDTO> memUsers = JSONObject.parseArray(userInfoJson, KitePosUserDTO.class);
            KitePosUserDTO userDto = memUsers.get(0);

            KitePosRelationDTO relationDto = new KitePosRelationDTO();

            List<Map<String, Object>> relationRoles = relationRoleList.stream().filter(role -> (
                KiteStringUtils.equals((String) role.get("MEM_GOODS_CLASSIFY_ID"), userDto.getOfferCatagoryId())
                    || KiteStringUtils.equals((String) role.get("MEM_GOODS_CLASSIFY_ID"), "-1")))
                .collect(Collectors.toList());

            if (!KiteListUtils.isEmpty(relationRoles)) {
                Map relationRole = relationRoles.get(0);
                relationDto.setRelationTypeCode(KiteMapUtils.getString(relationRole, "RELATION_TYPE_CODE"));
                relationDto.setPrimaryRoleCode(KiteMapUtils.getString(relationRole, "PRIMARY_ROLE_CODE"));
                relationDto.setMemRoleCode(KiteMapUtils.getString(relationRole, "MEM_ROLE_CODE"));

                if (KiteStringUtils.equalsAny(kiteSceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_JOIN)) {
                    Date createDate = kiteSceneInst.getCreateDate();
                    relationDto.setStartTime(KiteDateUtils.formatDate(createDate, KiteDateUtils.DATE_TIME_FORMAT_14));
                } else {
                    relationDto.setStartTime(userDto.getOpenDate());
                }

                relationDto.setPrimarySerialNumber(mainUsers.get(0).getSerialNumber());
                relationDto.setPrimaryUserId(mainUsers.get(0).getUserId());
                relationDto.setEndTime(KiteMapUtils.getString(relationRole, "END_DATE"));
                relationDto
                    .setUserInstId(CommonUtil.getInstanceId(LocalKeyConsts.YH_INST_CODE, userDto.getInstanceId()));
                relationDto.setPrimaryProvinceCode(mainUsers.get(0).getProvinceCode());
                relationDto.setPrimaryEparchyCode(mainUsers.get(0).getCityCode());
                relationDto.setDiscntPriority(String.valueOf(index));
                relationDto.setChangeType(userDto.getChangeType());

                if (KiteStringUtils.equalsAny(kiteSceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_JOIN)) {
                    relationDto.setChangeType(ChangeTypeUtils.CHANGE_TYPE_A);
                } else if (KiteStringUtils.equalsAny(kiteSceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_QUIT)) {
                    relationDto.setChangeType(ChangeTypeUtils.CHANGE_TYPE_D);
                    relationDto.setEndTime(KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_TIME_FORMAT_14));
                }
                relationDto.setInstanceId(this.genInstanceId(userDto.getInstanceId(), context.getPosDto().getRelations()));

                relations.add(relationDto);

                index++;
            }
        }
        context.getPosDto().setRelations(relations);
    }
}
